import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('../pages/login.vue'),
  },
  {
    path: '/',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue'),
      },
      {
        path: '/menu',
        component: () => import('../views/menu/menu.vue'),
        meta: {
          title: '菜单管理'
        }
      },
      {
        path: '/role',
        component: () => import('../views/role/role.vue'),
        meta: {
          title: '角色管理'
        }
      },
      {
        path: '/admin',
        component: () => import('../views/admin/admin.vue'),
        meta: {
          title: '管理员管理'
        }
      },
      {
        path: '/cate',
        component: () => import('../views/cate/cate.vue'),
        meta: {
          title: '商品分类'
        }
      },
      {
        path: '/specs',
        component: () => import('../views/specs/specs.vue'),
        meta: {
          title: '商品规格'
        }
      },
      {
        path: '/goods',
        component: () => import('../views/goods/goods.vue'),
        meta: {
          title: '商品管理'
        }
      },
      {
        path: '/member',
        component: () => import('../views/member/member.vue'),
        meta: {
          title: '会员管理'
        }
      },
      {
        path: '/banner',
        component: () => import('../views/banner/banner.vue'),
        meta: {
          title: '轮播图管理'
        }
      },
      {
        path: '/seckill',
        component: () => import('../views/seckill/seckill.vue'),
        meta: {
          title: '秒杀活动'
        }
      },
      {
        path: '*',
        redirect: '/home'
      }
    ]
  },
  {
    path: '/*',
    redirect: '/'
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next();
    return;
  }

  let userInfo = sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')) : null;
  if (!userInfo) {
    next('/login');
    return;
  }

  userInfo.menus_url.push('/home')
  if (!userInfo.menus_url.find(item => item == to.path)) {
    Message.error('您没有访问权限');
    next(from.path);
    return;
  }

  next();
})

export default router
